"""
用户账户相关的功能：注册、短信、登录、注销
"""
import uuid
import datetime
from io import BytesIO
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect, reverse

from web import models
from utils.imagecode.image_code import check_code
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm


def register(request):
    """注册"""
    if request.method == 'POST':
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            # 通过验证，写入数据库（密码要密文）

            # 用户表中新建一条数据（注册）
            instance = form.save()

            # 创建交易记录
            # 方式一（跟auth.py中方式一对应）
            policy_obj = models.PriceStrategy.objects.filter(category=1, title='个人免费版').first()
            models.Transaction.objects.create(
                status=1,
                order=str(uuid.uuid4()),
                user=form.instance,
                price_policy=policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()
            )

            # 方式二（跟auth.py中方式二对应）

            return JsonResponse({'status': True, 'data': reverse('web:login')})
        return JsonResponse({'status': False, 'error': form.errors})
    form = RegisterModelForm()
    return render(request, 'register.html', {'form': form})


def send_sms(request):
    """发送短信"""
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号，不能为空，格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'POST':
        form = LoginSMSForm(data=request.POST)
        if form.is_valid():
            # 用户输入正确，登陆成功（手机号、验证码）,接受用户对象
            user_obj = form.cleaned_data['mobile_phone']
            # 用户信息放入session中
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 12)
            return JsonResponse({'status': True, 'data': reverse('web:index')})
        return JsonResponse({'status': False, 'error': form.errors})
    form = LoginSMSForm()
    return render(request, 'login_sms.html', {'form': form})


def image_code(request):
    """获取验证码图片"""
    img, code = check_code()

    request.session['image_code'] = code
    # session_id: 60s后失效，主动修改session的过期时间为60s
    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def login(request):
    """用户名和密码登录"""
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # （手机=手机 and 密码=密码）or（邮箱=邮箱 and 密码=密码）
            user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).\
                filter(password=password).first()
            if user_obj:
                # 登录成功
                request.session['user_id'] = user_obj.id
                request.session.set_expiry(60 * 60 * 24 * 12)
                return redirect(reverse('web:index'))
            form.add_error('username', '用户名或密码错误')
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request)
    return render(request, 'login.html', {'form': form})


def logout(request):
    """退出"""
    request.session.flush()
    return redirect(reverse('web:index'))


